<?php
/**
 * Created by PhpStorm.
 * User: 睿
 * Date: 2017-11-09
 * Time: 9:12
 */

namespace app\store\controller;

use controller\BasicAdmin;
use service\DataService;
use think\Db;
use app\store\model\StoreOrderGoods;

class Order extends BasicAdmin
{
    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'StoreOrder';

    /**
     * 订货单列表
     * @return array
     */
    public function index()
    {
        $this->title = '订货单管理';
        $get = $this->request->get();

        $store_id = session('user')['store_id'];

        $db = Db::name($this->table)->order('id', 'desc')->where('store_id', $store_id)->where('type', 'in', '0,1')->where('is_diannei',0);
        foreach (['sn'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }

        return parent::_list($db);
    }

    public function detail()
    {
        $join = [
            ['ys_goods m', 'a.goods_id=m.id', 'LEFT'],
            ['ys_goods_spec_detail s', 'a.goods_spec_id=s.id', 'LEFT'],
        ];

        $db = db('StoreOrderGoods')->alias('a')->join($join)->where('order_id', input('id'))->field('a.*,m.*,s.*,m.good_number')->select();
        $order = db('store_order')->where('id',input('id'))->find();
        $store = db('store')->where('id',$order['store_id'])->find();

        $this->assign('list', $db);
        $this->assign('order', $order);
        $this->assign('store', $store);

        return $this->_form('store_material', 'detail');
    }

    public function rdetail()
    {
        $join = [
            ['ys_goods_material m', 'a.material_id=m.id', 'LEFT'],
        ];
        $db = db('store_material_order')->alias('a')->join($join)->where('order_id', input('id'))->select();
        $this->assign('list', $db);

        return $this->_form('store_material_order', 'form');
    }

    public function apply()
    {
        $db = db('store_material_apply')->where('order_id', input('id'))->select();
        $this->assign('list', $db);

        return $this->_form('store_material_order', 'apply');
    }


    /**
     * 追加原材料
     * @return array|string
     */
    public function add()
    {
        $store_id = session('user')['store_id'];
        if (request()->ispost()) {
            $order_id = input('id');
            $insert = db('store_material_order')->insert(['material_id' => input('material_id'), 'num' => input('num'), 'store_id' => $store_id, 'addtime' => time(), 'order_id' => $order_id, 'type' => 1]);
            if ($insert !== false)
                $this->success('原料追加成功！', '');
        } else {
            $db = db('goods_material')->where('is_deleted', 0)->select();
            $this->assign('list', $db);

            return $this->_form($this->table, 'add');
        }
    }


    /**
     * 提交
     */
    public function sub()
    {
        if (DataService::update($this->table)) {
            $this->success("提交成功！", '');
        }
        $this->error("提交失败，请稍候再试！");
    }

    /**
     * 确认收货
     * @return array|string
     * @throws \think\Exception
     */
    public function receive()
    {

        $store_id = session('user')['store_id'];

        if (request()->ispost()) {
            $post = input();

            $status = 1;//监控循环报错
            foreach ($post as $k => $v) {
                if (strrpos($k, 'num')) {
                    $id = explode('_', $k)[2];
                    $order_goods = db('store_order_goods')->where('id', $id)->find();
                    $i = db('store_order_goods')->update(['id' => $id, 'rec_num' => $v, 'dif_num' => $v - $order_goods['del_num'], 'rec_time' => time()]);
                    if ($i === false)
                        $status = 0;
                    //入库数大于0
                    if ($v > 0) {
                        $order_id = $post['order_id'];
                        $store_order = db('store_order')->where('id', $order_id)->find();
                        $sn = $store_order['sn'];

                        $store_goods_stock = db('store_goods_stock')->where('store_id', $store_id)->where('goods_id', $order_goods['goods_id'])->where('goods_spec_id' , $order_goods['goods_spec_id'])->find();
                        $title = $store_goods_stock['spec_title'];
                        if ($store_goods_stock) {
                            $ii = db('store_goods_stock')->where('id', $store_goods_stock['id'])->setInc('stock', $v);

                            $stock = $store_goods_stock['stock'] + $v;
                        } else {
//                            $goods_spec_detail = db('goods_spec_detail')->find($order_goods['goods_spec_id']);
//                            $ii = db('store_goods_stock')->insert([
//                                'store_id' => $store_id,
//                                'goods_id' => $order_goods['goods_id'],
//                                'goods_spec_id' => $order_goods['goods_spec_id'],
//                                'onsale' => 1,
//                                'stock' => $v,
//                                //追加
//                                'spec_title' => $goods_spec_detail['title'],
//                                'specs' => $goods_spec_detail['specs']
//                            ]);
//                            $stock = $v;
                            $goods_spec_detail = db('goods_spec_detail')->find($order_goods['goods_spec_id']);
                            $title = $goods_spec_detail['title'];
                            $ii = db('store_goods_stock')->insert([
                                'store_id' => $order_goods['store_id'],
                                'goods_id' => $order_goods['goods_id'],
                                'goods_spec_id' => $order_goods['goods_spec_id'],
                                'price'=>$goods_spec_detail['price'],
                                'onsale' => 0,
                                'stock' => $v,
                                //追加
                                'spec_title' => $goods_spec_detail['title'],
                                'specs' => $goods_spec_detail['specs'],
                                'addtime'=>time(),
                                'is_diannei'=>$order_goods['is_diannei'],
                                'is_deleted'=>0
                            ]);
                            $stock = $v;
                        }

                        if ($ii === false)
                            $status = 0;

//                        $log = [
//                            'store_id' => $store_id,
//                            'goods_id' => $order_goods['goods_id'],
//                            'goods_spec_id' => $order_goods['goods_spec_id'],
//                            'ruku_num' => $v,
//                            'remark' => $sn,
//                            'addtime' => time(),
//                            'cur_stock' => $stock,
//                        ];
                        $log = [
                            'store_id' => $order_goods['store_id'],
                            'goods_id' => $order_goods['goods_id'],
                            'goods_spec_id' => $order_goods['goods_spec_id'],
                            'title' => $title,
//                            'order_id' => $order_goods['order_id'],
                            'types' => 1,
                            'ruku_num' => $v,
//                            'remark' => $sn,
                            'remark' => '入库'.$v,
                            'addtime' => time(),
                            'cur_stock' => $stock,
                        ];
                        $iii = db('store_goods_log')->insert($log);
                        if ($iii === false)
                            $status = 0;
                    }
                }
            }

            if (db('store_order')->update(['id' => $post['order_id'], 'status' => 3,'receive_time'=>time(),'receive_admin'=>session('user.id')])!==false && $status==1)
                $this->success('收货成功', '');

        } else {
            $join = [
                ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
                ['ys_goods_spec_detail s', 'a.goods_spec_id=s.id', 'LEFT'],
            ];
            $db = db('store_order_goods')->alias('a')->join($join)->where('order_id', input('id'))->field('a.id as oid,a.*,g.*,s.*')->select();

            $this->assign('list', $db);
            $this->assign('order_id', input('id'));

            return $this->_form('store_material_order', 'receive');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    订单对账
     * 2018-06-04
     */
    public function dz_chengben(){
        if(request()->isPost()){
            $post = input('post.');
            $dz_chengben = 0;
            foreach($post['id'] as $k => $v){
                $data[$k]['id'] = $v;
                $data[$k]['dz_signal_chengben'] = $post['dz_signal_chengben'][$k];
                $data[$k]['dz_chengben'] = $post['dz_chengben'][$k];
                $dz_chengben+=$post['dz_chengben'][$k];
            }
            $model = new StoreOrderGoods();
            $model->saveAll($data);         //更新对账成本
            $res = db('store_order')->where('id',$post['order_id'])->update(['dz_chengben'=>$dz_chengben,'dz_admin'=>session('user.id'),'dz_time'=>time()]);
            $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $order_id = input('id');
            $join = [
                ['ys_goods b','a.goods_id=b.id','LEFT'],
                ['ys_goods_spec_detail c','a.goods_spec_id=c.id','LEFT']
            ];

            $order = db('store_order')->where('id',$order_id)->field('id,sn,chengben')->find();
            $order_goods = db('store_order_goods')->alias('a')->join($join)->where('a.order_id',$order_id)->field('a.*,a.id as oid,b.name,c.title')->select();

//            $this->assign('title','对账'.$order['sn']);
            $this->assign('order_id',$order_id);
            $this->assign('list',$order_goods);
            return $this->fetch();
        }
    }


}